package com.sls.game.service.impl;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.parser.nutsnet.BalanceResponseSaxParseXml;
import com.sls.game.parser.nutsnet.NutsNetAssembleHttpUrl;
import com.sls.game.parser.nutsnet.NutsNetServerSaxParseXml;
import com.sls.game.pojo.NutsNetBalanceQueryParameter;
import com.sls.game.pojo.NutsNetBalanceResInfo;
import com.sls.game.pojo.NutsNetServerInfo;
import com.sls.game.service.NutsNetBalanceQueryService;

/**
 * 
 * @description 合作伙伴用户Sup余额查询接口
 * @author Wangxuegang
 * @date 2012-9-4
 * 
 */
@Service("nutsNetBalanceQueryService")
public class NutsNetBalanceQueryServiceImpl implements
		NutsNetBalanceQueryService {

	private static Logger log = Logger
			.getLogger(NutsNetBalanceQueryServiceImpl.class);

	private Gson gson = null;

	public NutsNetBalanceQueryServiceImpl() {
		gson = CommonUtil.gson();
	}

	/**
	 * 合作伙伴用户Sup余额查询接口
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryBalance(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		NutsNetBalanceQueryParameter paraInfo = gson.fromJson(body,
				NutsNetBalanceQueryParameter.class);

		NutsNetServerInfo serverInfo = NutsNetAssembleHttpUrl.getKeyValue();
		String partnerKey = serverInfo.getPartnerKey(); // 为合作方商户密钥
		if (StringUtils.isNotEmpty(partnerKey)) {
			partnerKey = partnerKey.trim();
		}
		String supUserKey = serverInfo.getSupUserKey(); // 为合作方用户密钥
		if (StringUtils.isNotEmpty(supUserKey)) {
			supUserKey = supUserKey.trim();
		}
		String partnerId = serverInfo.getPartnerId(); // 合作平台编号
		if (StringUtils.isNotEmpty(partnerId)) {
			partnerId = partnerId.trim();
			paraInfo.setPartnerId(partnerId);
		}

		this.validate(paraInfo);
		boolean flag = checkData(paraInfo, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				// 签名字符串
				String sign = createSignStr(paraInfo, partnerKey, supUserKey);
				if (!("".equals(sign)) && sign != null) {
					paraInfo.setSign(sign);
				}

				String paraStr = assembleParameter(paraInfo);
				// 坚果网络接口服务path
				String path = "CheckUser.aspx";
				String url = NutsNetAssembleHttpUrl.assembleHttpUrl(paraStr,
						path);
				// 发送http请求
				NutsNetBalanceResInfo resInfo = sendHttpRequest(url, head);
				String resultBody = null;
				if (resInfo != null) {
					resultBody = gson.toJson(resInfo);
				}
				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.info("Service处理[" + head.getRequestId() + "]异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}

		}

		return null;
	}

	/**
	 * 用户账号查询
	 */
	@Override
	public String querySupUserId(Head head) throws ServerDisponseException {
		String filePath = "conf" + File.separator + "nutsNetServer.xml";
		List<NutsNetServerInfo> list = NutsNetServerSaxParseXml
				.parseXmlString(filePath);
		if (list != null && list.size() > 0) {
			return gson.toJson(list);
		} else {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_SUP_USER_ID_ERROR.getCode(),
					ExceptionCodeDes.PARSE_SUP_USER_ID_ERROR.getDescription());
		}
	}

	/**
	 * 生成签名字符串
	 * 
	 * @param paraInfo
	 * 
	 * @param partnerKey
	 * 
	 * @param supUserKey
	 * @return
	 */
	private String createSignStr(NutsNetBalanceQueryParameter paraInfo,
			String partnerKey, String supUserKey) {
		String partnerId = paraInfo.getPartnerId().trim();
		String supUserId = paraInfo.getSupUserId().trim();

		StringBuffer strBuf = new StringBuffer();
		strBuf.append("partnerId");
		strBuf.append(partnerId);
		strBuf.append("supUserId");
		strBuf.append(supUserId);
		strBuf.append(partnerKey);
		strBuf.append(supUserKey);

		String data = strBuf.toString();
		String signStr = UtilMD5Encryption.createMD5EncryptionOfGBK(data);
		if (StringUtils.isEmpty(signStr)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SIGN_ERROR.getCode(),
					ExceptionCodeDes.SIGN_ERROR.getDescription());
		}

		return signStr;
	}

	/**
	 * 校验是否为空
	 * 
	 * @param paraInfo
	 */
	private void validate(NutsNetBalanceQueryParameter paraInfo) {
		if (paraInfo == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
	}

	/**
	 * 数据校验
	 * 
	 * @throws ServerDisponseException
	 */
	private boolean checkData(NutsNetBalanceQueryParameter paraInfo,
			String reqId) throws ServerDisponseException {
		boolean flag = false;
		// 合作平台编号
		String partnerId = paraInfo.getPartnerId();
		// 合作方用户编号
		String supUserId = paraInfo.getSupUserId();
		if ("".equals(partnerId) || partnerId == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL
							.getDescription());
		} else if ("".equals(supUserId) || supUserId == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_USERNO_NULL.getCode(),
					ExceptionCodeDes.COOPERATION_USERNO_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * http请求url所传参数字符串拼接
	 * 
	 * @param parameterInfo
	 * @return
	 */
	private String assembleParameter(NutsNetBalanceQueryParameter paraInfo) {
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("partnerId=");
		strBuf.append(paraInfo.getPartnerId().trim());
		strBuf.append("&");
		strBuf.append("supUserId=");
		strBuf.append(paraInfo.getSupUserId().trim());
		strBuf.append("&");
		strBuf.append("sign=");
		strBuf.append(paraInfo.getSign());

		String paraStr = strBuf.toString();
		return paraStr;
	}

	/**
	 * 发送http请求，并对返回的xml格式的结果进行解析
	 * 
	 * @param url
	 * @return
	 */
	private NutsNetBalanceResInfo sendHttpRequest(String url, Head head) {
		log.info("请求ID:" + head.getRequestId() + "坚果网络余额查询请求url：" + url);
		NutsNetBalanceResInfo resInfo = null;
		HttpClient httpClient = new HttpClient();
		try {
			String supplyEncode = "GBK";
			String xmlStr = httpClient.doGet(url, supplyEncode);
			log.info("请求ID:" + head.getRequestId() + "坚果网络余额查询响应结果：" + xmlStr);
			// 对返回的xml格式字符串数据进行解析
			List<NutsNetBalanceResInfo> balResList = BalanceResponseSaxParseXml
					.parseXmlString(xmlStr);
			if (balResList.size() > 0) {
				for (int i = 0; i < balResList.size(); i++) {
					resInfo = balResList.get(i);
				}

				return resInfo;
			}

		} catch (Exception e) {
			log.error(e);
		}

		return null;
	}

}
